package com.boot.crm.http;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: crm_boot
 * @author: yangshen
 * @description: 处理完业务逻辑之后 将结果传递给需调用的接口
 * @create: 2020-05-27 14:36
 **/
@Controller
public class ResolveBusinessAfterSendHttp {

    /**
     * http://10.241.65.88:32413/push-service
     */
    @Value("${publis.service}")
    private String path;

    @RequestMapping("/afterSendHttp")
    public String afterSendHttp(@Param("jsonObject") JSONObject jsonObject){
        //业务逻辑的处理
        //JSONObject jsonObject = questionnaireOnlineRecommendSystemService.queryOnlineTemplate(id, cmd);
        //String encryption = getEncryption(USER_ID, LOG_ID);

        RestTemplate client = new RestTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        headers.add("userId","");
        headers.add("logId","");
        headers.add("sign","");
        //设置请求发送方式
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交, 发送JSON格式数据  **** 看情况
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(jsonObject, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化（可设置为对应返回值格式的类）
        ResponseEntity<String> response = client.exchange(path, method, requestEntity,String.class);
        return response.getBody();
    }

    private String getEncryption(String userId, String logId) throws Exception {
        String waitEncryptStr = String.format("userId=%s&logId=%s&wdxx_rec_service", userId, logId);
        return getMD5Str(waitEncryptStr);
    }

    public static String getMD5Str(String str) throws Exception {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("String to encrypt cannot be null or zero length");
        }
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            for (byte b : hash) {
                if ((0xff & b) < 0x10) {
                    hexString.append("0").append(Integer.toHexString((0xFF & b)));
                } else {
                    hexString.append(Integer.toHexString(0xFF & b));
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hexString.toString();
    }
}
